﻿using System;
using System.ComponentModel;
using System.Linq;

namespace SharpShare.Afp.Protocol.Security {
    [DisplayName("Clear Text")]
    [Description("This UAM sends password in clear text, making it the least secure. This UAM can not handle passwords longer than 8 characters.")]
    public class AfpCleartextUserAuthenticationMethod : IAfpUserAuthenticationMethod {
        public string Name {
            get { return AfpUams.kClearTextUAMStr; }
        }

        public AfpUserAuthenticationResult Authenticate(IAfpSession session, string version, string path, string username, AfpStream authInfoStream) {
            authInfoStream.ReadPadding();
            byte[] passwordBytes = authInfoStream.ReadBytes(8).TakeWhile(b => b > 0).ToArray();
            string password = System.Text.Encoding.ASCII.GetString(passwordBytes);

            IAfpUser user = session.Server.UserManager.GetUser(username);
            if (user == null || !user.Authenticate(password))
                return new AfpDenyUserAuthenticationResult();

            return new AfpAllowUserAuthenticationResult(version, this.Name, user);
        }

        public AfpUserAuthenticationResult ContinueAuthentication(IAfpSession session, short id, AfpStream authInfoStream) {
            throw new NotImplementedException();
        }
    }
}
